package com.tjetc.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class Db {
    private static DataSource dataSource;
    static {
        try {
            Properties properties = new Properties();
            InputStream inputStream = Db.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(inputStream);
            dataSource= DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static QueryRunner runner=new QueryRunner(dataSource);
    private static ThreadLocal<Connection> local=new ThreadLocal<>();

    public static Connection getConnection() {
        try {
            Connection connection=local.get();
            if (connection==null){
                connection= dataSource.getConnection();
                local.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void start(){
        try {
            getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void commit(){
        try {
            getConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void rollback(){
        try {
            getConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(){
        try {
            getConnection().close();
            //事务连续用时，用这个
            local.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
